package cn.easybuy.servlet.Cart;

import cn.easybuy.entity.BuyCar;

import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/addCartServlet")
public class AddCartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String img = req.getParameter("img");
        int id = Integer.parseInt(req.getParameter("id"));
        String name = req.getParameter("name");
        float price = Float.parseFloat(req.getParameter("price"));
        int quantity = Integer.parseInt(req.getParameter("quantity"));
        BuyCar buyCar = new BuyCar(img,id,name,price,quantity);
        buyCar.setSum(price,quantity);
        float sum = 0;
        List<BuyCar> list =(List<BuyCar>)req.getSession().getAttribute("listCarSession");
        if(list==null){
            list =new ArrayList<>();
        }
        list.add(buyCar);
        for (int i = 0; i < list.size(); i++) {
            sum+=list.get(i).getSum();
        }
        req.getSession().setAttribute("sum",sum);
        req.getSession().setAttribute("listCarSession",list);
        req.getSession().setAttribute("size",list.size());
        req.getRequestDispatcher("/productgongServlet").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
